package com.design3.graduatethesissys.configure;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.design3.graduatethesissys.controller.Chuqi;
import com.design3.graduatethesissys.domain.SysUser;
import com.design3.graduatethesissys.mapper.SysUserMapper;
import com.design3.graduatethesissys.service.impl.UserServiceImpl;

/** 
* @author 作者 罗穆健: 
* @version 创建时间：2020年1月5日 下午5:23:22 
* 类说明 
*/
@Service
public class MyAuthenticationProvider implements AuthenticationProvider {
	/**
	* 注入我们自己定义的用户信息获取对象
	*/
	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Autowired
	private SysUserMapper sysUserMapper;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		// TODO Auto-generated method stub
		String userName = authentication.getName();// 这个获取表单输入中返回的用户名;
		String password = (String) authentication.getCredentials();// 这个是表单中输入的密码；
		// 这里构建来判断用户是否存在和密码是否正确
		User userInfo = (User) userServiceImpl.loadUserByUsername(userName); // 这里调用我们的自己写的获取用户的方法；
		if (userInfo == null) {
			throw new BadCredentialsException("用户名不存在");
		}
		
		PasswordEncoder encoder = new BCryptPasswordEncoder();
		if (!encoder.matches(password,userInfo.getPassword())) {
			throw new BadCredentialsException("密码不正确");
		}
		Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();
		Map<String, String> aMap = new HashMap<String, String>();
		aMap.put("username", userInfo.getUsername());		
		aMap.put("name",sysUserMapper.findNameByUserName(userInfo.getUsername()));
		// 构建返回的用户登录成功的token
		return new UsernamePasswordAuthenticationToken(aMap, password, authorities);
	}
	@Override
	public boolean supports(Class<?> authentication) {
		// 这里直接改成retrun true;表示是支持这个执行
		return true;
	}
}